layui.use(['form', 'layer'], function(){
    var $ = layui.jquery;
    var form = layui.form;
    var layer = layui.layer;
    
    var countdown = 180;
    var timer = null;
    // 初始化clipboard.js
    var clipboard = new ClipboardJS('.copy-btn');
   
    clipboard.on('success', function(e) {
        layer.msg('复制成功');
        return false;
    });clipboard.on('error', function(e) {
        layer.msg('复制失败，请手动复制');
        return false;
    });
    $(document).ready(function() {
        $('#intepaypwd').on('click', function() {
            intepaypwd();
        });
    });
    window.intepaypwd = function(){
        layer.open({
            type: 1,
            title: '支付密码验证',
            area: ['400px', '250px'],
            content: `
                <div style="padding:20px;">
                    <form class="layui-form">
                    <div class="layui-form-item">
                        <label class="layui-form-label">支付密码</label>
                        <div class="layui-input-block">
                            <input type="password" name="paypass" placeholder="请输入支付密码" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item" style="margin-top: 30px;">
                        <div class="layui-input-block">
                            <button class="layui-btn" lay-submit lay-filter="verifypaypwd">效验</button><button type="reset" class="layui-btn layui-btn-primary" onclick="layer.closeAll()">
                                取消
                            </button>
                        </div>
                    </div>
                    </form>
                </div>
            `,
            success: function(){
                form.render();
                
                // 监听验证表单提交
                form.on('submit(verifypaypwd)', function(data){
                    // 处理表单提交逻辑
                    $.ajax({
                        url: './ajax/verifypaypwd',
                        type: 'POST',
                        data: data.field,
                        dataType: 'json',
                        success: function(res){
                            if(res.code === 200){
                                layer.msg(res.msg, {
                                    icon: 1,
                                    time: 1000
                                }, function() {
                                    layer.closeAll();
                                    location.reload();
                                });
                                
                            }else{
                                layer.msg(res.msg || '修改失败', {icon: 2});
                                refreshCaptcha();
                            }
                        },
                        error: function(){
                            layer.msg('服务器错误', {icon: 2});
                            refreshCaptcha();
                        }
                    });
                    return false;
                });
            }
        });
    }
    function screen() {
        var width = $(window).width() * 0.8;
        var height = $(window).height() * 0.8;
        return [width + 'px', height + 'px'];
    }
    // 显示验证对话框
    window.showVerifyDialog = function(type) {
        
        var typedata ={
            'email':"邮箱",
            'phone':"手机号",
            'pass':"密码",
            'pay_pass':"支付密码"
            
        };
        layer.open({
            type: 1,
            title: '配置' + typedata[type],
            area: ['480px', '400px'], 
            content: `
                <div style="padding: 20px;">
                    <form class="layui-form" id="verifyForm">
                        <div class="layui-form-item">
                            <label class="layui-form-label">新${typedata[type]}</label>
                            <div class="layui-input-block">
                                <input type="hidden" name="type" value="${type}" class="layui-input">
                                <input type="${(type == 'pass' || type == 'pay_pass') ? 'password':"text" }" name="newvalue"  required lay-verify="required" placeholder="请输入新的${typedata[type]}" class="layui-input">
                            </div>
                        </div>
                
                        <!-- 添加图形验证码 --><div class="layui-form-item">
                            <label class="layui-form-label">图形验证</label>
                            <div class="layui-input-block" style="display: flex;">
                                <input type="text" name="captcha" required lay-verify="required" 
                                       placeholder="请输入图形验证码" class="layui-input"style="width: calc(100% - 130px); margin-right: 10px;"><img id="captchaImg" src="/api/captcha" alt="验证码"style="height: 38px; width: 120px; cursor: pointer;"onclick="this.src='/api/captcha?t='+new Date().getTime()">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">验证码</label>
                            <div class="layui-input-block" style="display: flex;">
                                <input type="text" name="verify_code" required lay-verify="required" 
                                       placeholder="请输入验证码" class="layui-input"style="width: calc(100% - 130px); margin-right: 10px;">
                                <button type="button" class="verify-code-btn" onclick="sendVerifyCode('${type}')">
                                    获取验证码
                                </button>
                            </div>
                        </div>
                        <div class="layui-form-item" style="margin-top: 30px;">
                            <div class="layui-input-block">
                                <button class="layui-btn" lay-submit lay-filter="verifySubmit">确认修改</button><button type="reset" class="layui-btn layui-btn-primary" onclick="layer.closeAll()">
                                    取消
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            `,
            success: function(){
                form.render();
                
                // 监听验证表单提交
                form.on('submit(verifySubmit)', function(data){
                    // 处理表单提交逻辑
                    $.ajax({
                        url: './ajax/update_contact',
                        type: 'POST',
                        data: data.field,
                        dataType: 'json',
                        success: function(res){
                            if(res.code === 200){
                                layer.msg(res.msg, {
                                    icon: 1,
                                    time: 1000
                                }, function() {
                                    layer.closeAll();
                                    location.reload();
                                });
                                
                            }else{
                                layer.msg(res.msg || '修改失败', {icon: 2});
                                refreshCaptcha();
                            }
                        },
                        error: function(){
                            layer.msg('服务器错误', {icon: 2});
                            refreshCaptcha();
                        }
                    });
                    return false;
                });
            }
        });
    }

    // 刷新图形验证码
    window.refreshCaptcha = function() {
        $('#captchaImg').attr('src', '/api/captcha?t=' + new Date().getTime());
    }

    // 发送验证码
    window.sendVerifyCode = function(type) {
        var newValue = $(`input[name="newvalue"]`).val();
        var captcha = $('input[name="captcha"]').val();
        
        if(!newValue){
            layer.msg('请先输入新的' + (type === 'email' ? '邮箱' : '手机号'), {icon: 2});
            return;
        }
        
        if(!captcha){
            layer.msg('请先输入图形验证码', {icon: 2});
            return;
        }

        // 先验证图形验证码
        $.ajax({
            url: './ajax/verify_captcha',
            type: 'POST',
            data: {
                captcha: captcha
            },
            dataType: 'json',
            success: function(res){
                if(res.code == 200){
                    sendSmsCode(type, newValue ,captcha );
                }else{
                    layer.msg(res.msg || '图形验证码错误', {icon: 2});
                    refreshCaptcha();
                }
            },
            error: function(){
                layer.msg('服务器错误', {icon: 2});
                refreshCaptcha();
            }
        });
    }

    // 发送短信验证码
    function sendSmsCode(type, newValue , captcha) {
        var $btn = $('.verify-code-btn');
        $btn.attr('disabled', true);
        countdown = 180;
        timer = setInterval(function(){
            if(countdown > 0){
                $btn.text(`${countdown}秒后重试`);
                countdown--;
            }else{
                clearInterval(timer);
                $btn.removeAttr('disabled').text('获取验证码');
            }
        }, 1000);

        $.ajax({
            url: './ajax/send_verify_code',
            type: 'POST',
            data: {
                type: type,
                value: newValue,
                captcha:captcha
            },
            dataType: 'json',
            success: function(res){
                if(res.code == 200){
                    layer.msg(res.msg, {icon: 1});
                }else{
                    layer.msg(res.msg || '发送失败', {icon: 2});
                    clearInterval(timer);
                    $btn.removeAttr('disabled').text('获取验证码');
                    refreshCaptcha();
                }
            },
            error: function(){
                layer.msg('服务器错误', {icon: 2});
                clearInterval(timer);
                $btn.removeAttr('disabled').text('获取验证码');
                refreshCaptcha();
            }
        });
    }
    form.on('submit(formsubmit)', function(data){
        $.ajax({
            url: './ajax/edit_userinfo',
            data:JSON.stringify(data.field),
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json',
            success: function(res){
                if(res.code == 200){
                    layer.msg(res.msg, {
						icon: 1,
						time: 1000
					}, function() {
						location.reload();
					});
                }else{
                    layer.msg(res.msg, {icon: 2});
                }
            },
            error: function(){
                layer.msg('服务器错误', {icon: 2});
            }
        });
        return false;
    });
    form.on('submit(generateRsaKeys)', function(data){
        layer.open({
            type: 1,
            title: '支付密码验证',
            area: ['400px', '250px'],
            content: `
                <div style="padding:20px;">
                    <form class="layui-form">
                    <div class="layui-form-item">
                        <label class="layui-form-label">支付密码</label>
                        <div class="layui-input-block">
                            <input type="password" name="paypass" placeholder="请输入支付密码" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item" style="margin-top: 30px;">
                        <div class="layui-input-block">
                            <button class="layui-btn" lay-submit lay-filter="verifypaypwd">效验</button><button type="reset" class="layui-btn layui-btn-primary" onclick="layer.closeAll()">
                                取消
                            </button>
                        </div>
                    </div>
                    </form>
                </div>
            `,
            success: function(){
                form.render();
                // 监听验证表单提交
                form.on('submit(verifypaypwd)', function(data){
                    // 处理表单提交逻辑
                    $.ajax({
                        url: './ajax/create_userrsa',
                        type: 'POST',
                        dataType: 'json',
                        data:data.field,
                        success: function(res){
                            if(res.code == 200){
                                layer.closeAll()
                                layer.open({
                                    type: 1,
                                    title: `请注意保存私钥 后续将不会在展示`,
                                    area: ['480px', '400px'],
                                    shadeClose: true,
                                    content: `
                                        <div style="padding:20px;">
                                            <div class="key-item">
                                                <div class="key-value"><textarea class="key-textarea" readonly>${res.rsaprivatekey}</textarea>
                                                    <button class="copy-btn" data-clipboard-text="${res.rsaprivatekey}">
                                                        <i class="layui-icon layui-icon-file" title="复制"></i>
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    `,
                                    end: function() {
                                        location.reload();  
                                    }
                                });
                                
                            }else{
                                layer.msg(res.msg, {icon: 2});
                            }
                        },
                        error: function(){
                            layer.msg('服务器错误', {icon: 2});
                        }
                    });
                    return false;
                });
            }
        });
        
        
        return false;
    });
    form.on('submit(resetKey)', function(data){
        layer.confirm('确定要重置商户KEY吗？', {
            btn: ['确定','取消']
        }, function(){
               $.ajax({
                url: './ajax/resetKey',
                type: 'POST',
                dataType: 'json',
                success: function(res){
                    if(res.code == 200){
                        layer.msg(res.msg, {
    						icon: 1,
    						time: 1000
    					}, function() {
    						location.reload();
    					});
                    }else{
                        layer.msg(res.msg, {icon: 2});
                    }
                },
                error: function(){
                    layer.msg('服务器错误', {icon: 2});
                }
            });
       
        });
        return false;
    });
});
